package org.visionlibrary.image.filters.effects;

import java.util.Random;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;


public class Melt extends AbstractFilter {
	@Override
	public TiledImage applyFilter(final TiledImage src, TiledImage dest) {
		if (null == src)
			throw new NullPointerException("Source image is null.");

		if (null == dest)
			dest = (new ImageFactory()).createCompatibleImage(src);
		
		final int maxX = src.getWidth();
		final int maxY = src.getHeight();

		Random random = new Random();

		// TODO Dokonczyc!!! i poprawic ponizej
		// dest.copyData(src.getWritableTile(0, 0)); DOPISAC!!

		for (int i = 0; i < 1000; i++) {
			int xcord = Math.abs(random.nextInt(maxX - 1));
			int ycord = Math.abs(random.nextInt(maxY - 2));

			// to avoid nullpointerexception
			if (xcord >= maxX)
				xcord = maxX - 1;

			if (ycord >= maxY - 2)
				ycord = maxY - 3;

			for (int ch = 0; ch < src.getNumBands(); ch++) {
				int px = src.getSample(xcord, ycord, ch);
				int dpx = src.getSample(xcord, ycord + 1, ch);
				if (px < dpx) {
					dest.setSample(xcord, ycord, ch, dpx);
					dest.setSample(xcord, ycord + 1, ch, px);
				}
			}

		}
		return dest;
	}
}
